package historymanager.tools;

import java.util.Date;
import org.apache.log4j.Logger;

/**
 * This class implements the singleton-pattern.
 * @author Thomas Aulich
 *
 */
public class MeasurePointRequestorController {
	static Logger log = Logger.getLogger(MeasurePointRequestorController.class);
	private static MeasurePointRequestorController instance;
	private static MeasurePointRequestor measurePointRequestor;
	private static Thread measurePointRequestorThread;
	private Configuration config;
	private Date myBirthDate;

	/**
	 * Private constructor to implement Singleton-Pattern
	 */
	private MeasurePointRequestorController() {
		// Remember the time, when instance was created
		myBirthDate = new Date();
		config = Configuration.getInstance();
		log.debug("Configuration was born at:"
				+ String.valueOf(config.getBirthDate()));
	}

	public static MeasurePointRequestorController getInstance() {
		if (instance == null) {
			// Singleton with double-checked locking
			synchronized (MeasurePointRequestorController.class) {
				if (instance == null) {
					instance = new MeasurePointRequestorController();
					instance.requestorStart();
				}
			}
		}
		return instance;
	}

	public Date getBirthDate() {
		return myBirthDate;
	}
	
	public static boolean requestorRunning() {
		if (measurePointRequestor == null || measurePointRequestorThread == null) {
			return false;
		} else {
			return true;
		}
	}

	public void requestorStop() {
		if (measurePointRequestor != null) {
			measurePointRequestor.stop();
			measurePointRequestor = null;
			measurePointRequestorThread.interrupt();
		}
	}
	
	public void requestorStart() {
		if (measurePointRequestor == null) {
			measurePointRequestor = new MeasurePointRequestor(instance);
			measurePointRequestorThread = new Thread(
					measurePointRequestor);
			measurePointRequestorThread.start();
			log.debug("measurePointRequestorThread started ...");
		}		
	}
}
